<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" v-on:change="changeKeyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getUsers">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="60">
			</el-table-column>
			<el-table-column prop="" label="序号" type="index" width="55">
			</el-table-column>
      <el-table-column prop="id" label="ID" width="70" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="100" sortable>
        <el-avatar shape="square" style="background: #13ce66" :size="40" :src="url"></el-avatar>
      </el-table-column>
			<el-table-column prop="username" label="姓名" width="100" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="220" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="100" sortable>
			</el-table-column>
			<el-table-column prop="dept.name" label="部门" width="120" sortable>
			</el-table-column>
      <el-table-column prop="role.name" label="角色" width="120" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination 
			layout="total,prev, pager, next"
			@current-change="handleCurrentChange" 
			:page-size="query.pageSize" 
			:total="pageInfo.total" 
			:current-page="query.currentPage"
			style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑/新增界面-->
		<el-dialog title="编辑员工信息" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="saveForm.email"></el-input>
        </el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="saveForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
        <el-form-item label="部门">
<!--          <el-input v-model="saveForm.dept.id"></el-input>-->
          <el-cascader
              v-model="saveForm.dept.id"
              :options="deptTree"
              :props="{
                checkStrictly: true,
                label:'name',
                value:'id'
              }"
              @change="handleChange"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="saveForm.role.id" placeholder="请选择">
            <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
					username: ''
				},
				Employees: [],
        deptTree: [],
				listLoading: false,
				sels: [],//列表选中列
        roles: [],  // 角色列表

				saveFormVisible: false,//编辑界面是否显示
				editLoading: false,
				saveFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				saveForm: {
					id: null,
					username: '',
          email: '',
					age: 0,
					dept: {
            id: null,
            name: ''
          },
          role: {
            id: null,
            name: '',
          }
				},
				query: {
					currentPage: 1,	// 当前页，默认第一页
					pageSize : 10,// 每页展示数据，默认10条
					keyword: ""// 关键字-查询条件
				},
				pageInfo: {
					total: 0,// 总条数
					rows:[] // 当前页数据
				},
        url: "require(../../assets/1.jpg)",
			}
		},
		methods: {
      handleChange(val) {
        // 当部门选择框发生变变化时将最后一个父部门id值赋值给dept对象的id
        let para = Object.assign({},this.saveForm)
        if (para.dept) {
          para.dept={"id":val[val.length-1]}
        }
        this.saveForm = para;
        console.log(val)
      },
      changeKeyword(val) {
        this.getEmpList();
      },
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getEmpList();
			},
			//获取用户列表
			getUsers() {
        this.query.currentPage = 1;
        this.getEmpList();
			},
      // 获取所有角色信息
      getRoles() {
        this.$http.get("/role")
          .then(result => {
            result = result.data;
            if (result.success) {// true 后端返回了数据
              this.roles = result.data;
            } else {// 后端处理失败
              this.$message({message: result.message,type: 'error'});
            }
          })
          .catch(result => {
            this.$message({message: "网络错误："+result,type: 'error'});
          })
      },
			//删除
			handleDel(index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {type: 'warning'})
          .then(() => {
            this.$http.delete("/emp/"+row.id)
              .then(result => {
                result = result.data;
                if (result.success) {// true 后端返回了数据
                  this.$message({message: result.message,type: 'success'});
                  this.query.currentPage = 1;
                  this.getEmpList();
                } else {// 后端处理失败
                  this.$message({message: result.message,type: 'error'});
                }
              })
              .catch(result => {
                this.$message({message: "网络错误："+result,type: 'error'});
              })
            console.log(row)
          })
          .catch(() => {
            this.$message({message: "你取消了删除",type: 'info'})
          });
			},
      getDeptTree() {
        this.$http.get("/dept/tree")
          .then(result => {
            result = result.data;
            if (result.success) {// true 后端返回了数据
              this.deptTree = result.data;
            } else {// 后端处理失败
              this.$message({message: result.message,type: 'error'});
            }
          })
          .catch(result => {
            this.$message({message: "网络错误："+result,type: 'error'});
          })
      },
      //显示编辑界面
			handleEdit(index, row) {
				this.saveFormVisible = true;
        console.log("数据回显",row)
				this.saveForm = Object.assign({}, row);
        // 特殊处理manager parent
        // 如果manager parent没有值,为null的话,就给它们赋一个初识对象
        if(!this.saveForm.dept){
          this.saveForm.dept = {
            id:null,
            name: ""
          }
        }
        if (!this.saveForm.role) {
          this.saveForm.role = {
            id: null,
            name: '',
          }
        }
        console.log("数据回显22",this.saveForm)
        // 部门回显
        this.getDeptTree();
        // 角色回显
        this.getRoles();
			},
			//新增界面
			handleAdd() {
				this.saveFormVisible = true;
				this.saveForm = {
          id: null,
          username: '',
          email: '',
          age: 0,
          dept: {
            id: null,
            name: ''
          },
          role: {
            id: null,
            name: ''
          }
				};
        this.temp = [];
        // 获取部门树
        this.getDeptTree();
        // 获取角色
        this.getRoles();
			},
			//编辑
			editSubmit() {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {})
              .then(() => {
                this.editLoading = true;  // 加载框
                // 调用接口
                console.log("提交数据：",this.saveForm)
                this.$http.put("/emp",this.saveForm)
                  .then(result => {
                    result = result.data;
                    if (result.success) {// true 后端返回了数据
                      this.$message({message: result.message,type: 'success'});
                    } else {// 后端处理失败
                      this.$message({message: result.message,type: 'error'});
                    }
                    this.editLoading = false;
                    this.saveFormVisible = false;
                    this.getUsers();
                  })
                  .catch(result => {
                    alert("网络错误！"+result)
                  })
                console.log(this.saveForm)
              })
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				let ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
          .then(() => {
            console.log(ids)
            this.$http.patch("/emp",ids)
              .then(result => {
                result = result.data;
                if (result.success) {// true 后端返回了数据
                  this.$message({message: result.message,type: 'success'});
                } else {// 后端处理失败
                  this.$message({message: result.message,type: 'error'});
                }
                this.query.currentPage = 1;
                this.getEmpList();
              })
              .catch(result => {
                alert("网络错误！"+result)
              })
          })
          .catch(() => {
            this.$message({message: "你取消了删除",type: 'info'})
          });
			},
			// 获取分页数据
			getEmpList() {
				console.log(this.query);
				this.$http.post("/emp", this.query)
					.then(result => {
						console.log(result);
						result = result.data;
						if (result.success) {// true 后端返回了数据
							this.pageInfo = result.data;
						} else {// 后端处理失败
              this.$message({message: result.message,type: 'error'});
            }
					})
          .catch(result => {// 连接后端接口失败
            alert("网络错误！"+result)
          })
			}
		},
		mounted() {
			this.getEmpList();
		}
	}

</script>

<style scoped>

</style>